package com.wms.entity;

import com.wms.entity.OperationLog;
import com.wms.mapper.OperationLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Resource
    private OperationLogMapper operationLogMapper;

    @AfterReturning(pointcut = "@annotation(com.wms.entity.OperationLogAnnotation)", returning = "result")
    public void saveOperationLog(JoinPoint joinPoint, Object result) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            com.wms.entity.OperationLogAnnotation annotation = method.getAnnotation(com.wms.entity.OperationLogAnnotation.class);

            // 获取参数
            Object[] args = joinPoint.getArgs();
            Integer orderId = null;
            String note = null;

            for (Object arg : args) {
                if (arg instanceof com.wms.dto.AllocatedetailAuditVo) {
                    com.wms.dto.AllocatedetailAuditVo vo = (com.wms.dto.AllocatedetailAuditVo) arg;
                    orderId = vo.getOrderId();
                    note = vo.getNote();
                    break;
                }
            }

            com.wms.entity.OperationLog logEntity = new com.wms.entity.OperationLog();
            logEntity.setOrderId(orderId);
            logEntity.setOperationType(2); // 审核
            logEntity.setOperatorId(1001); // 假设从 session 或 security 里拿
            logEntity.setOperatorName("系统用户");
            logEntity.setOperationTime(new Date());
            logEntity.setNote(annotation.description() + (note != null ? " - " + note : ""));
            operationLogMapper.insert(logEntity);

            log.info("AOP记录操作日志成功: {}", logEntity);

        } catch (Exception e) {
            log.error("保存操作日志失败", e);
        }
    }
}